<template>
    <div class="manage-page">
        <el-card>
            <h2>后台管理中心</h2>
            <el-tabs v-model="activeTab">
                <!-- 用户管理 -->

                <el-tab-pane label="用户管理" name="users">
                    <el-button type="primary" @click="openUserDialog()">新建用户</el-button>
                    <el-table :data="userList" v-loading="loading" stripe style="margin-top:10px">
                        <el-table-column prop="username" label="用户名" width="140" />
                        <!-- <el-table-column label="头像" width="80">
                            <template #default="scope">
                                <el-avatar :src="scope.row.avatar_url" />
                            </template>
                        </el-table-column> -->
                        <el-table-column label="管理员" width="90">
                            <template #default="scope">
                                <el-tag :type="Number(scope.row.manage) === 1 ? 'success' : ''">
                                    {{ Number(scope.row.manage) === 1 ? '是' : '否' }}
                                </el-tag>
                            </template>
                        </el-table-column>

                        <el-table-column label="操作" width="180">
                            <template #default="scope">
                                <el-button size="small" @click="openUserDialog(scope.row)">编辑</el-button>
                                <el-button size="small" type="danger" @click="deleteUser(scope.row)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>

                    <!-- 用户增改对话框 -->
                    <el-dialog v-model="userDialogVisible" :title="userEditMode ? '编辑用户' : '新建用户'">
                        <el-form :model="userForm" label-width="80px">
                            <el-form-item label="用户名">
                                <el-input v-model="userForm.username" :disabled="userEditMode" />
                            </el-form-item>
                            <el-form-item label="密码">
                                <el-input v-model="userForm.password" type="password"
                                    :placeholder="userEditMode ? '留空不改密码' : '必填'" />
                            </el-form-item>
                            <!-- <el-form-item label="头像">
                                <input type="file" accept="image/*" @change="onUserImgChange" />
                                <img v-if="userForm.avatar_url" :src="userForm.avatar_url"
                                    style="width:36px; margin-left:8px;">
                            </el-form-item> -->
                            <el-form-item label="管理员">
                                <el-switch v-model="userForm.manage" :active-value="1" :inactive-value="0"></el-switch>
                            </el-form-item>
                        </el-form>
                        <template #footer>
                            <el-button @click="userDialogVisible = false">取消</el-button>
                            <el-button type="primary" @click="saveUser">保存</el-button>
                        </template>
                    </el-dialog>
                </el-tab-pane>


                <!-- 讨论区留言管理 -->
                <el-tab-pane label="讨论区留言管理" name="messages">
                    <el-select v-model="currentArea" placeholder="选择分区" style="width:180px;margin-bottom:12px">
                        <el-option v-for="zone in zones" :key="zone.key" :label="zone.title" :value="zone.key" />
                    </el-select>
                    <el-table :data="msgList" stripe>
                        <el-table-column prop="id" label="ID" width="60" />
                        <el-table-column prop="username" label="用户" width="120" />
                        <el-table-column prop="content" label="内容" />
                        <el-table-column prop="created_at" label="时间" width="180" />
                        <el-table-column prop="likes" label="点赞" width="80" />
                        <el-table-column label="操作" width="100">
                            <template #default="scope">
                                <el-button size="small" type="danger" @click="deleteMessage(scope.row)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>

                <!-- 分区管理 -->
                <el-tab-pane label="分区管理" name="zones">
                    <el-button type="primary" icon="el-icon-plus" @click="openZoneDialog()">新建分区</el-button>
                    <el-table :data="zones" style="margin-top:20px">
                        <el-table-column prop="key" label="Key" width="120" />
                        <el-table-column prop="title" label="标题" width="150" />
                        <el-table-column prop="desc" label="描述" />
                        <el-table-column label="操作" width="180">
                            <template #default="scope">
                                <el-button size="small" @click="openZoneDialog(scope.row)">编辑</el-button>
                                <el-button size="small" type="danger" @click="deleteZone(scope.row.key)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>

                    <!-- 新建/编辑分区对话框 -->
                    <el-dialog v-model="zoneDialogVisible" :title="zoneEditMode ? '编辑分区' : '新建分区'">
                        <el-form :model="zoneForm" label-width="80px">
                            <el-form-item label="分区Key">
                                <el-input v-model="zoneForm.key" :disabled="zoneEditMode" />
                            </el-form-item>
                            <el-form-item label="分区标题">
                                <el-input v-model="zoneForm.title" />
                            </el-form-item>
                            <el-form-item label="分区描述">
                                <el-input v-model="zoneForm.desc" />
                            </el-form-item>

                        </el-form>
                        <template #footer>
                            <el-button @click="zoneDialogVisible = false">取消</el-button>
                            <el-button type="primary" @click="saveZone">保存</el-button>
                        </template>
                    </el-dialog>
                </el-tab-pane>
            </el-tabs>
        </el-card>
    </div>
</template>

<script setup>
import { ref, onMounted, watch, reactive } from 'vue'
import axios from '../utils/axios.js'

// 用户列表
const userList = ref([])
const loading = ref(false)

// 查询用户（查）
const fetchUsers = async () => {
    loading.value = true
    const res = await axios.get('/users/full')
    userList.value = res.data.data || []
    loading.value = false
    console.log('userList', userList.value)
}

// 新建/编辑用户对话框
const userDialogVisible = ref(false)
const userEditMode = ref(false) // false=新建，true=编辑
const userForm = reactive({
    id: null,
    username: '',
    password: '',
    avatar_url: '',
    manage: 0
})

// 删除留言
async function deleteMessage(row) {
    if (!confirm(`确定删除留言 #${row.id} 吗？`)) return
    await axios.delete(`/messages/${row.id}`)
    fetchMessages(currentArea.value)
}

// 打开对话框
function openUserDialog(row = null) {
    if (row) {
        Object.assign(userForm, row)
        userForm.password = '' // 编辑时密码不预填
        userEditMode.value = true
    } else {
        Object.assign(userForm, {
            id: null,
            username: '',
            password: '',
            avatar_url: '',
            manage: 0
        })
        userEditMode.value = false
    }
    userDialogVisible.value = true
}

// 新建/保存用户（增、改）
async function saveUser() {
    if (!userForm.username) {
        alert('用户名不能为空'); return
    }
    if (!userEditMode.value && !userForm.password) {
        alert('新建用户时密码不能为空'); return
    }
    // 编辑
    if (userEditMode.value) {
        await axios.put(`/users/${userForm.id}`, userForm)
    } else {
        await axios.post('/users', userForm)
    }
    userDialogVisible.value = false
    fetchUsers()
}

// 删除用户
async function deleteUser(row) {
    if (!confirm(`确定删除用户 ${row.username}？`)) return
    await axios.delete(`/users/${row.id}`)
    fetchUsers()
}

// 上传头像（可选，参考个人中心）
const onUserImgChange = async (e) => {
    const file = e.target.files[0]
    if (!file) return
    const formData = new FormData()
    formData.append('file', file)
    const res = await fetch('http://localhost:5000/upload_avatar', {
        method: 'POST',
        credentials: 'include',
        body: formData,
    })
    const data = await res.json()
    if (data.status === 'success') {
        userForm.avatar_url = data.data.avatar
        alert('头像上传成功！')
    } else {
        alert('上传失败')
    }
}
// Tab切换
const activeTab = ref('users')

// ---------- 分区管理 ----------
const zones = ref([])
const fetchZones = async () => {
    const res = await axios.get('/zones')
    zones.value = res.data.data || []
}
const zoneDialogVisible = ref(false)
const zoneEditMode = ref(false)
const zoneForm = ref({ key: '', title: '', desc: '', image: '' })
function openZoneDialog(row = null) {
    if (row) {
        Object.assign(zoneForm.value, row)
        zoneEditMode.value = true
    } else {
        zoneForm.value = { key: '', title: '', desc: '', image: '' }
        zoneEditMode.value = false
    }
    zoneDialogVisible.value = true
}
async function saveZone() {
    if (!zoneForm.value.key || !zoneForm.value.title) {
        alert('Key和标题不能为空')
        return
    }
    if (zoneEditMode.value) {
        await axios.put(`/zones/${zoneForm.value.key}`, zoneForm.value)
    } else {
        await axios.post('/zones', zoneForm.value)
    }
    zoneDialogVisible.value = false
    fetchZones()
}
async function deleteZone(key) {
    if (confirm('确定要删除该分区？')) {
        await axios.delete(`/zones/${key}`)
        fetchZones()
    }
}
function beforeUpload(file) {
    const isImg = file.type.startsWith('image/')
    if (!isImg) alert('只能上传图片')
    return isImg
}

// ---------- 留言管理 ----------
const msgList = ref([])
const currentArea = ref('')
async function fetchMessages(area) {
    if (!area) return
    const { data } = await axios.get('/messages', { params: { area } })
    msgList.value = Array.isArray(data) ? data : []
}
watch(currentArea, fetchMessages)
watch(zones, () => {
    if (zones.value.length && !currentArea.value) {
        currentArea.value = zones.value[0].key
    }
})

// Tab切换时刷新
watch(activeTab, (tab) => {
    if (tab === 'users') fetchUsers()
    if (tab === 'messages' && currentArea.value) fetchMessages(currentArea.value)
    if (tab === 'zones') fetchZones()
})

onMounted(() => {
    fetchUsers()
    fetchZones()
})
</script>

<style scoped>
.manage-page {
    max-width: 950px;
    margin: 30px auto;
}
</style>
